package com.jf.controller;

import com.alibaba.fastjson.JSON;
import com.jf.util.MyUtils;
import com.jf.util.ResultJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/upload")
/*MultipartConfig注解让servlet拥有处理文件上传的能力*/
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*获取操作类型，不同模块上传的文件，进行不同文件夹的存储*/
        String type = request.getParameter("type");
        /*未设置操作类型则默认存入images文件夹*/
        if(MyUtils.isStringEmpty(type)){
            type="images";
        }
        /*根据表单元素的name值获取文件对象*/
        Part part = request.getPart("file");
        /*获取项目在Tomcat中的绝对地址*/
        String uploadPath = request.getServletContext().getRealPath("/");
        /*获取当前的年月*/
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        /*拼接存放图片的地址*/
        String filePath = "upload/"+type+"/"+year+"/"+(month<10?"0"+month:month)+"/";
        //地址不存在则创建，这里不创建，最后写入文件时会报错
        File file = new File(uploadPath+filePath);
        /*验证文件夹地址是否存在*/
        if(!file.exists()){
            /*不存在则创建文件夹*/
            file.mkdirs();
        }
        // 拼接最终的文件名，用于存入数据库字段
        String fileName = filePath+MyUtils.getFileName()+"."+MyUtils.getFileType(part.getSubmittedFileName());
        // 拼接存入硬盘的路径
        String savePath = uploadPath+"/"+fileName;
        // 文件存入指定位置
        part.write(savePath);
        // 封装返回的json
        Map<String,String> map = new HashMap<>();
        map.put("fileName",fileName);
        response.getWriter().println(JSON.toJSON(ResultJson.success(map)));
    }
}
